var SwordTab = new Class({
    Implements : [Events,Options],
    $family: {name: 'SwordTab'},
    name:"SwordTab",
    options:{
        name:null,
        pNode:null,
        sword:null,
        tabType:null,//tab的类型,iframe和div这两种类型
        tabTitles:null,//tab的标题名称
        tabSelectedIndex:0,//tab的默认选中的序号,默认为0
        tabDivs:null,//tab的div类型的id数组
        tabIframes:null,//tab的iframe类型的id数组
        tabContentWidth: null,//宽度
        tabContentHeight: null,//高度
        tabDirection: "up",//tab的方向,一共分为2个方向,up,left
        onSelect: null,
        isRefresh:"false",//是否强制刷新
        onSelectedShowAfter:null
//        maxChars:10 //页签上显示的最大字符数,超过后显示省略号
        ,initLoad:"true"// 是否初始化加载第一序列页签
        ,autoHeight:'false'//是否在初始化的时候自动计算iframe内容的高度并设置给tab页，此时tabContentHeight将不生效
        ,isEnables:''
        ,isEditables:''
        ,autoCountHeight:'false'
        ,quickKey:'alt+q'
    },
    styles:{
        "tabsUL":"tabs_ul",
        "tabsLI":"tabs_li",
        "tabsLICommon":"tabs_li_common" ,    //li未被选中样式
        "tabsLISelect":"tabs_li_select",   //li被选中样式
        "outertabsDiv":"outer_tabs_div",
        "divHidden":"divHidden"
    },
    tabMaskDiv:null,
    tabDivs:[],//下面这两个tabDivs,tabIframes是数组的引用
    tabIframeDivs:[],
    tabIframes:[],
    tabSwordWiget:[],
    initialize:function(options) {
        this.setOptions(options);
    },
    setRefresh:function(bool) {
        if(bool == true)this.options.isRefresh = "true";
        if(bool == false)this.options.isRefresh = "false";
    },
    initParam: function(node) {
        this.htmlOptions(node);
        node.erase('onSelect');//解决和原生事件冲突的问题
        if(this.options.tabTitles != null) this.options.tabTitles = this.options.tabTitles.split(",");
        if(this.options.tabDivs != null) this.options.tabDivs = this.options.tabDivs.split(",");
        if(this.options.tabIframes != null) this.options.tabIframes = this.options.tabIframes.split(",");
        this.options.pNode = node;
        this.defineStyles();
        this.createTab();
        if(this.options.isEnables!=""){
        	this.options.isEnables.split(",").each(function(item,index){
        		if(item=="true"){
        			this.setTabdivDisOrEnClick(index,"enable");
        		}else{
        			 this.setTabdivDisOrEnClick(index,"disable");
        		}
        	}.bind(this));
        }if(this.options.isEditables!=""){
        	this.options.isEditables.split(",").each(function(item,index){
        		if(item=="true"){
        			this.setTabdivDisOrEnEdit(index,"editable");
        			
        		}else{
        			this.setTabdivDisOrEnEdit(index,"readonly");
        			if(index==this.options.tabSelectedIndex) this.setTabdivDisOrEnEdit.delay(1,this,[this.options.tabSelectedIndex,"readonly"]);
        		
        		}
        	}.bind(this));
        	
        }
        if(this.options.autoCountHeight=="true"){
        	this.siach = window.setInterval(this.autoHeight.bind(this),200);//创建定时器
        }
    },
    initData: function() {

    },
    defineStyles: function() {
    	  if(this.options.tabDirection == "up") {  
              this.styles.tabsUL = this.styles.tabsUL + "_horizontal";
              this.styles.tabsLI = this.styles.tabsLI + "_horizontal";
              this.styles.tabsLICommon = this.styles.tabsLICommon + "_horizontal";
              this.styles.tabsLISelect = this.styles.tabsLISelect + "_horizontal";
              this.styles.outertabsDiv = this.styles.outertabsDiv + "_horizontal";
          } 
          else if(this.options.tabDirection == "left"  ) {
              this.styles.tabsUL = this.styles.tabsUL + "_vertical";
              this.styles.tabsLI = this.styles.tabsLI + "_vertical";
              this.styles.tabsLICommon = this.styles.tabsLICommon + "_vertical";
              this.styles.tabsLISelect = this.styles.tabsLISelect + "_vertical";
              this.styles.outertabsDiv = this.styles.outertabsDiv + "_vertical";
           
          }
//          else if(this.options.tabDirection == "right"){
//              this.styles.tabsUL = this.styles.tabsUL + "_vertical_r";
//              this.styles.tabsLI = this.styles.tabsLI + "_vertical_r";
//              this.styles.tabsLICommon = this.styles.tabsLICommon + "_vertical_r";
//              this.styles.tabsLISelect = this.styles.tabsLISelect + "_vertical_r";
//              this.styles.outertabsDiv = this.styles.outertabsDiv + "_vertical_r";
//          	this.options.pNode.setStyle("float","right");
//          	
//          }

    },
	computeTitleSize: function(title){
//		var actualLength = 0; sword5
//		var ml = this.options.maxChars;
//		if(title.length > ml){
//			for(var i = 0 ; i < title.length; i++){
//				if(/^[\u4e00-\u9fa5]+$/i.test(title.charAt(i))){
//					actualLength = actualLength + 2;//汉字加2
//				}else{
//					actualLength ++;
//				}
//			}
//		}
//		return actualLength > 0 ? (title.substring(0,ml) + "..") : title;
		return  title;
	},
    createTab: function() {
        var headerDiv = new Element('div', {'class': 'bbbbox_top_bg'}).inject(this.options.pNode);
        var headerLDiv = new Element('div', {'class': 'l'}).inject(headerDiv);
        var headerRDiv = new Element('div', {'class': 'r'}).inject(headerDiv);
        var tabDiv = new Element('div', {'class' : 'tabs'});
        tabDiv.inject(headerDiv);
        var ulid = "SwordTab_"+this.options.name+"_ul";
    
        var ulTitle = new Element('ul', {'id': ulid,'class':  this.styles.tabsUL});
        this.options.tabTitles.each(function(item, index) {
            var liid = "SwordTab_"+this.options.name+"_li_"+index;
            var li = new Element('li', {'id'    : liid ,'class': '' + this.styles.tabsLI + ' ' + this.styles.tabsLICommon}).inject(ulTitle);
            var tempDivid = "SwordTab_"+this.options.name+"_div_"+index;
            var tempDiv = new Element('div', {
                'id'    : tempDivid,
                'html': this.computeTitleSize(this.options.tabTitles[index]),
                'title': this.options.tabTitles[index]
            	
            }).inject(li);
            li.addEvent('click', function(e) {
            	if(tempTabDiv.hasClass(this.styles.divHidden))  tempTabDiv.removeClass(this.styles.divHidden);//initLoad=false的时候需要隐藏显示内容点击tab才显示  sword5
                //this.fireEvent('onSelect', this);
            	if(li.get("isDisable")=="true")return;
            	var tempIndex = this.options.tabSelectedIndex;
            	var ay = new Event(e).target.get('id').split("_");
                this.options.tabSelectedIndex = ay[ay.length-1];
                if(this.options.onSelect) {
                    if(this.getFunc(this.options.onSelect)[0](this, tempIndex, this.options.tabSelectedIndex) != false) {
                        this.options.tabSelectedIndex = tempIndex;
                        this.selectIndex(e);
                        if(this.options.onSelectedShowAfter)
                        	this.getFunc(this.options.onSelectedShowAfter)[0](this, tempIndex, this.options.tabSelectedIndex);
                    } else {
                        this.options.tabSelectedIndex = tempIndex;
                    }
                } else {
                    this.selectIndex(e);
                    if(this.options.onSelectedShowAfter)
                    	this.getFunc(this.options.onSelectedShowAfter)[0](this, tempIndex, this.options.tabSelectedIndex);
                }
                //是否蒙板
               
	            var selectDiv=this.tabDivs[this.options.tabSelectedIndex]||this.tabIframeDivs[this.options.tabSelectedIndex];
	            if(Browser.Engine.trident4){
	            	this.tabMaskDiv.setStyles({left:  selectDiv._getPosition().x,top: selectDiv._getPosition().y,width: selectDiv.offsetWidth,height: selectDiv.offsetHeight+1});
	            }else{
	            	this.tabMaskDiv.setStyles({left:  selectDiv.offsetLeft,top: selectDiv.offsetTop-1,width: selectDiv.offsetWidth,height: selectDiv.offsetHeight+1});
	            }
	            if(selectDiv.get("isMask")=="true")this.tabMaskDiv.setStyle("display","block");
	            else this.tabMaskDiv.setStyle("display","none");
            }.bind(this));
            li.addEvent('mouseover', function(e) {

            }.bind(this));
            li.addEvent('mouseout', function(e) {

            }.bind(this));
        }.bind(this));
        //ulTitle.inject(tabDiv);
		if(this.options.tabContentHeight&&this.options.tabContentHeight.contains('%')){
			this.options.tabContentHeight=$(document.body).getHeight()*(this.options.tabContentHeight.replace('%','')/100);
		}
		var h = this.options.tabContentHeight;
		if(h!=null){
			 h = h +"";
			  if(!h.contains('px')) {
				  h += 'px';
		      }
		}
		
		  var w = this.options.tabContentWidth;
		  if(w!=null){
			  w = w + '';
			  if(!(w.contains('%') || w.contains('px'))) {
				  w += 'px';
		      }
		  }
        var tempTabDiv = new Element('div', {
            'id'    : 'SwordTab_'+this.options.name+"_div",
            'class':this.styles.outertabsDiv,
            'styles': {
                'width': w,
                'height': h
            }
        }).inject(tabDiv);
        
		if(this.options.initLoad=="false") tempTabDiv.addClass(this.styles.divHidden);//initLoad=false的时候需要隐藏显示内容点击tab才显示 sword5
		
        if(this.options.tabType == 'div') {
            this.options.tabDivs.each(function(item, index) {
                $(item).setStyle("display", "none");
                this.tabDivs[index] = $(item);
                //tempTabDiv.adopt($(item));
            }.bind(this));
        } else {
            this.options.tabIframes.each(function(item, index) {
                var tempIframeDiv = new Element('div', {
                    'id'    : "SwordTab_"+this.options.name+"_iframeDiv_"+index,
                    'class':this.styles.outertabsDiv,
                    'styles': {
                        'width': '100%',
                        'height': '100%'
                    }
                });
                var tempIframe = new Element('iframe', {
                    'id'    : "SwordTab_"+this.options.name+"_iframe_"+index,
                    //'src'    : this.options.tabIframes[index],
                    'allowTransparency':'true',
                    'frameborder':0,
                    'styles': {
                        'border':'0px',
                        'width':'100%',
                        'height': '100%'
                    }
                });
                tempIframe.inject(tempIframeDiv);
                tempIframeDiv.inject(tempTabDiv);
                if(Browser.Engine.trident) {
                    window.frames['SwordTab_'+this.options.name+'_iframe_' + index].document.write("<style type='text/css'>body{background-color:#ecf5f7;}</style>");
                }
                this.tabIframeDivs[index] = tempIframeDiv;
                this.tabIframes[index] = tempIframe;
                tempIframeDiv.setStyle("display", "none");
            }.bind(this));
        }
//        if(this.options.tabDirection == "up" || this.options.tabDirection == "left") {  sword5
            if($defined(ulTitle))
                ulTitle.inject(tabDiv, 'top');

//        } 
//        else if(this.options.tabDirection == "down" || this.options.tabDirection == "right") {
//
//            if($defined(ulTitle))
//                ulTitle.inject(tabDiv);
//        }
        this.tabMaskDiv=new Element('div',{styles:{'z-index': '30000',
    		'visibility': 'visible',
    		'opacity': '0.1',
    		'position': 'absolute',
    		'display': 'none', 
    		'background': 'none repeat scroll 0% 0% gray'}}).inject(this.options.pNode,'before'); 
        if(this.options.initLoad=="true")this.selectIndex(this.options.tabSelectedIndex);
    },
    $:function (id) {
        return $(id);//this.options.pNode.getElement('[id=' + id + ']');此方法由于html结构调整,so修改成直接返回id元素
    },
    selectIndex: function(index) {
        if(($type(index) == 'event')) {
        	var ay = new Event(index).target.get('id').split("_");
            index = ay[ay.length-1];
        }
        if(this.options.tabSelectedIndex != index) {
            this.options.tabSelectedIndex = index;
        }
        this.options.tabTitles.each(function(item, index1) {
        	var li = 'SwordTab_'+this.options.name+'_li_' + index1;
            if(index != index1) {
                this.$(li).removeClass(this.styles.tabsLISelect);
                this.$(li).removeClass('tabs_li_over');
                this.$(li).addClass(this.styles.tabsLICommon);
            } else {
                this.$(li).removeClass(this.styles.tabsLICommon);
                this.$(li).removeClass('tabs_li_over');
                this.$(li).addClass(this.styles.tabsLISelect);
            }
        }.bind(this));
        if(this.options.tabType == 'div') {
            this.options.tabDivs.each(function(item, index1) {
                if(index != index1) {
                    $(item).setStyles({
                        'display':'none',
                        'clear': 'both'
                    }).addClass("tabs_div");
                    if(this.options.tabDirection == "left" ){
                		$(item).setStyle( 'clear','none');
                	}
                } else {
                    $(item).setStyles({
                        'position':'static',
                        'display':'',
                        'clear': 'both'
                       
                    }).addClass("tabs_div");
                    if(this.options.tabDirection == "left" ){
                		$(item).setStyle( 'clear','none');
                	}
                    if($(item).getAttribute('isload') != 'true') {
                        var swordWidgets = $(item).getElements("div[sword][sword!='PageInit'][isload!='true']");
                        swordWidgets.each(function(value) {
                            if(pc.isEdit()) {
                                pc.getEditor().addEl(value);
                            }
                            var swordWidget = pageContainer.widgetFactory.create(value.getAttribute('sword'));
                            value.pNode = value;
                            swordWidget.initParam(value);
                            pageContainer.widgets.set(value.get('name'), swordWidget);
                            swordWidget.initData(pc.getInitData(value.get('name')) || pageContainer.getResData(value.get('name'), pageContainer.pinitData));
                            if($type(this.tabSwordWiget[this.options.tabSelectedIndex]) != 'array') {
                                this.tabSwordWiget[this.options.tabSelectedIndex] = new Array();
                                this.tabSwordWiget[this.options.tabSelectedIndex][0] = value.get('name');
                            } else {
                            }
                        }, this);
                        $(item).set('isload', 'true');
                    }
                }
            }.bind(this));
        } else {
            this.options.tabIframes.each(function(item, index1) {
            	var Ifr = this.tabIframes[index1];
	            this.$('SwordTab_'+this.options.name+'_iframeDiv_' + index1).setStyles({
	                  "display": "none",
	                  'clear': 'both'
	            });
	            if(this.options.tabDirection == "left" ){
	                 this.$('SwordTab_'+this.options.name+'_iframeDiv_' + index1).setStyle( 'clear','none');
	            }
            }.bind(this));
            var Ifr = this.tabIframes[index];
            var item = this.options.tabIframes[index];
            if(this.options.isRefresh == "false") {
                if($defined(Ifr.src) && $defined(item)) {
                    if(Ifr.src != item) {
                        if(!$chk(Ifr.src)){
                        	 $try(function(){
                        	 	 var retFn = eval(item);
                        	 	 if($define(retFn)){
                        	 	 	 Ifr.src = retFn;
                        	 	 }else{
                        	 	 	 Ifr.src = item;
                        	 	 }
                        		 
                        	 },function(){
                        		 Ifr.src = item;
                        	 });
                        }
                    }
                }
            }else if(this.options.isRefresh=="true"){
                Ifr.src = item;
            }else{
                alert("SwordTab上定义了错误的isRefresh属性值！");
            }
            if(Browser.Engine.trident) { //if  IE
            	Ifr.addEvent('readystatechange', function(){
                    if (Ifr.readyState == "complete"){
                    	Ifr.isLoaded=true;
                    	$((this.contentDocument||this.contentWindow.document).body).setStyle("padding","0");
                    }
                });
         	} else {
            	Ifr.addEvent('load', function(){
            		Ifr.isLoaded=true;
         			$(this.contentDocument.body).setStyle("padding","0");
                });
            } 	
            this.$('SwordTab_'+this.options.name+'_iframeDiv_' + index).setStyles({
                "display": "block",
                'clear': 'both'
            });
            
        	if(this.options.tabDirection == "left"){
        		this.$('SwordTab_'+this.options.name+'_iframeDiv_' + index).setStyle( 'clear','none');
        	}
            //autoHeight
             if(this.options.autoHeight=='true'){
            	 
            	 if($chk(Ifr.contentWindow)&&$chk(Ifr.contentWindow.pc)){
                     var height =  Ifr.getStyle('height');
                     var scrollHeight=Ifr.contentWindow.document.body.scrollHeight+2;
                     if(height!=scrollHeight)Ifr.setStyle('height',scrollHeight);
            	 }else{
                	  if(!Browser.Engine.trident) { //if not IE
                    		Ifr.addEvent('load', function(){
                              this.autoHeight(Ifr);
                              
                           }.bind(this));
                     } else {
                          Ifr.addEvent('readystatechange', function(){
                               if (Ifr.readyState == "complete"){
                                      this.autoHeight.delay(1,this,[Ifr]);
                               }
                           }.bind(this));
                     } 
            	 }
             }
        
        }
        //if(this.options.tabType == 'iframe')this.tabIframeDivs[index].focus();

    },
    	
    	
    autoHeight:function(Ifr){
    	if(Ifr){	
    		var ifb = Ifr.contentWindow.document.body;
    		if(ifb){
	    		var html=$(ifb).getParent();
	    		html.setStyle('height','auto');
	    		var h = (document.all)?ifb.scrollHeight+2:ifb.offsetHeight+2;
	    		Ifr.setStyle('height',h);
    		}
    	}
    	else{
    		this.autoHeight(this.tabIframes[this.options.tabSelectedIndex]);
    	}
     },
    
    
    getSelectWigetNameArray: function(wigetName) {
        var nameArray = new Array();
        if(this.options.tabType == 'div') {
            this.tabDivs[this.options.tabSelectedIndex].getElements("div[sword][sword=" + wigetName + "]").each(function(item) {
                nameArray.include(item.getProperty('name'));
            });
        } else {
            alert("本方法只支持div");
        }
        return nameArray;
    },
    validateTab: function(index) {
        var flag = true;
        this.tabSwordWiget[index].each(function(item, index) {
            if(pageContainer.getWidget(item).validate() == false) {
                flag = false;
            }
        });
        return flag;
    },
    validateAllTab: function() {
        if(this.validateTab(this.options.tabSelectedIndex) == false) {
            return false;
        }
        for(var i = 0; i < this.options.tabTitles.length; i++) {
            if(i != this.options.tabSelectedIndex) {
                this.selectIndex(i);
                if(this.validateTab(i) == false) {
                    return false;
                }
            }
        }
    }

    //显示某个标签页
    ,show:function (index) {
        if(this.options.tabType != 'div')return;
        var li =this.options.pNode.getElementById('SwordTab_'+this.options.name+'_ul').getChildren()[index];
        if(li.hasClass("tabs_li_select_horizontal")){
        	   this.tabDivs[index].setStyle('display', '');
        }
        li.setStyle('display', '');
     
    }

    //隐藏某个标签页
    ,hide:function(index) {
        if(this.options.tabType != 'div')return;
        this.tabDivs[index].setStyle('display', 'none');
        this.options.pNode.getElementById('SwordTab_'+this.options.name+'_ul').getChildren()[index].setStyle('display', 'none');
    }
    //提供接口修改tab页名称
    ,setTabTitle:function(index, title){
    	var tab = this.options.pNode.getElement("div[id=SwordTab_"+this.options.name+"_div_"+index+"]");
    	if(tab){
    		tab.set('html',title);
    		tab.set('title',title);
    	}
    }
    //[不推荐使用，请使用disOrEnEdit]
    ,setTabdivDisOrEnEdit:function(index,state){
    	var mbDiv=this.tabDivs[index]||this.tabIframeDivs[index];
    	var l =  mbDiv.getPosition().x;
    	var t = mbDiv.getPosition().y;
    	this.tabMaskDiv.setStyles({left: l,top:t-1,width: mbDiv.offsetWidth,height: mbDiv.offsetHeight+1});
	    mbDiv.set("isMask","true");
		if(index==this.options.tabSelectedIndex)
			this.tabMaskDiv.setStyle("display","block");
		if(state=="editable"){
	   		mbDiv.set("isMask","false");
	   		if(index==this.options.tabSelectedIndex)this.tabMaskDiv.setStyle("display","none");
	   	}
    }
     //提供接口将指定的tab页禁用或启用，sword5
//     disOrEnEdit:function(index,state){
//          this.setTabdivDisOrEnEdit(index,state);
//     }

    //[不推荐使用，请使用disOrEnClick]
    ,setTabdivDisOrEnClick:function(index,state){
    	var li=this.options.pNode.getElement("li#SwordTab_"+this.options.name+"_li_"+index);
    	li.set("isDisable","true");
    	li.removeClass("tabs_li_common_horizontal").addClass("tabs_li_readonly_horizontal");
    	if(state=="enable"){
    		li.set("isDisable","false");
    		if(li.hasClass("tabs_li_select_horizontal")){
    			li.removeClass("tabs_li_readonly_horizontal");
    		}else{
    			li.removeClass("tabs_li_readonly_horizontal").addClass("tabs_li_common_horizontal");
    		}
    	}
    }
    //提供接口将指定tab页置灰,禁止点击。 sword5
//    ,disOrEnClick:function(index,state){ 
//         this.setTabdivDisOrEnClick(index,state);
//     }
    ,disable:function(index){
    	 this.setTabdivDisOrEnClick(index,"disable");
    }
    ,enable:function(index){
   	 this.setTabdivDisOrEnClick(index,"enable");
   }
    ,readonly:function(index){
     //   this.setTabdivDisOrEnEdit(index,"readonly");
        this.setTabdivDisOrEnEdit.delay(1,this,[index,"readonly"]);
   }
    ,editable:function(index){
        this.setTabdivDisOrEnEdit(index,"editable");
   },setTabContentHeight:function(height){
	   if(height.toInt()<1) return;
	   	var h = height;
	   	if(h!=null){
				 h = h +"";
				  if(!h.contains('px')) {
					  h += 'px';
			      }
			      
			var tds = "";
			if(this.options.tabType=="iframe"){
				tds = this.tabIframeDivs;
			}else{
				tds = this.tabDivs;
			}
		    tds.each(function(item,index){
		   		if(item.getStyle("display")!="none"){
		   			item.setStyle("height",h);
		   		}
		   	});
			}
   	}

});

